package com.apes.scm.masterdata.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductServiceHours;
import com.apes.scm.masterdata.product.repository.ProductServiceHoursRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.scm.masterdata.product.service
 * @ClassName: ProductServiceHoursService
 * @Author: pyb
 * @CreateTime: 2020-02-06 15:16
 * @Description: 商品服务工时
 * @Version: 1.0
 */
@Service("productServiceHoursService")
public class ProductServiceHoursService extends DomainService {
    @Autowired
    private ProductServiceHoursRepository productServiceHoursRepository;

    @Value("${apes.switched:false}")
    private Boolean switched;

    public static final String YYERP = "pi.yyerp.invoke";

    private ProductServiceHours save(SimpleRequest request) {
        ProductServiceHours serviceHours = request.getO(ProductServiceHours.class);
//        String userName = getSession(request).getUserName();
//        JSONObject data = new JSONObject();
//        data.put("type","save");
//        data.put("CZY",userName);
//        formatProductServiceHours(serviceHours,data);
//        if (!serviceHours.getId().equals("")){
//            data.put("type","updata");
//        }
//        synErp("mdmSpfwgsService.synFWGS", data);

        ProductServiceHours productServiceHours = null;
        try {
            productServiceHours = productServiceHoursRepository.saveAndFlush(serviceHours);
        } catch (Exception e) {
            if (e.getMessage().contains("ORA-00001"))throw new RuntimeException("该商品已存在服务工时，如有变更请根据商品编码或名称进行查询后在服务工时进行修改");
            throw new RuntimeException(e.getMessage());
        }
        return productServiceHours;
    }

    private String delete(SimpleRequest request) {
        ProductServiceHours serviceHours = request.getO(ProductServiceHours.class);
//        JSONObject data = new JSONObject();
//        data.put("type","delete");
//        formatProductServiceHours(serviceHours,data);
//        synErp("mdmSpfwgsService.synFWGS", data);
        productServiceHoursRepository.delete(serviceHours);
        return "删除成功";
    }

    /**
     * 手动同步至老系统
     * @param request
     * @return
     */
    private String synProductServiceHoursTest(SimpleRequest request) {
        JSONObject jo = request.getJO();
        Date startDate = jo.getDate("startDate");
        List<ProductServiceHours> createDateAfter = productServiceHoursRepository.findAllByCreateDateAfter(startDate);
        List<ProductServiceHours> createDateBeforeAndLastUpdatedStampAfter = productServiceHoursRepository.findAllByCreateDateBeforeAndLastUpdatedStampAfter(startDate, startDate);
        createDateAfter.forEach(serviceHours -> {
            String userName = getSession(request).getUserName();
            JSONObject data = new JSONObject();
            data.put("type","save");
            data.put("CZY",userName);
            formatProductServiceHours(serviceHours,data);
            synErp("mdmSpfwgsService.synFWGS", data);
        });

        createDateBeforeAndLastUpdatedStampAfter.forEach(serviceHours -> {
            String userName = getSession(request).getUserName();
            JSONObject data = new JSONObject();
            data.put("type","updata");
            data.put("CZY",userName);
            formatProductServiceHours(serviceHours,data);
            synErp("mdmSpfwgsService.synFWGS", data);
        });

        return "同步成功";
    }

    public Page<Map> queryProductServiceHours(SimpleRequest request){
        JSONObject jo = request.getJO();
        Long timestamp = jo.getLong("timestamp");

        Page<Map> resultList = productServiceHoursRepository.findAllByLastUpdatedStampAfter(new Date(timestamp),JpaDsl.getPageable(request));
        return resultList;

    }

    /**
     * 同步老系统
     *
     * @param method
     * @param body
     * @return
     */
    public JSONObject synErp(String method, Object body) {
        Map data = mapper("body", body, "headers", MapUtil.mapper("method", method));
        Object result = invoke(YYERP, data);
        JSONObject resultJo = JSONObject.parseObject(result.toString());
        if (!resultJo.getBoolean("success")) throw new RuntimeException(resultJo.getString("msg"));
        return resultJo;
    }


    /**
     * 格式化数据到老框架
     * @return
     */
    private JSONObject formatProductServiceHours(ProductServiceHours serviceHours,JSONObject data) {
        data.put("SPID",serviceHours.getProduct().getId());
        data.put("SPMC",serviceHours.getProduct().getName());
        data.put("SGSC",serviceHours.getServiceHours());
        data.put("YXBJ",serviceHours.isValid()?"1":"0");
        data.put("xxtbj","1");
        return data;
    }

    /**
     * 根据商品
     * @param product
     * @return
     */
    public int returnHourByProduct(Product product){
        List<ProductServiceHours> productServiceHours = productServiceHoursRepository.findAll(JpaDsl.toCriteriaByEq(
                "product.id",product.getId()
        ));
        if(productServiceHours == null || productServiceHours.size() == 0) return 0;

        return productServiceHours.stream().findFirst().get().getServiceHours()*60;
    }
}
